package com.javapig.util;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

/**
 * 以下处理jsp中出现中文乱码,对所有页面进行强制编码
 * 配置参数<p>
 * encoding 编码类型 （已经设成gbk）
 * @version 1.0
 * @author javapig
 */

public class Encode extends HttpServlet implements Filter {
  protected FilterConfig filterConfig;
  private String val_encoding;
  private ServletContext context;
  private String filterName;

  //Handle the passed-in FilterConfig
  public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig=filterConfig;
    val_encoding = filterConfig.getInitParameter("encoding");
    context = filterConfig.getServletContext();
    filterName = filterConfig.getFilterName();
  }

  //Process the request/response pair
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
   throws ServletException ,IOException
  {
    //try {
      request.setCharacterEncoding(val_encoding);
      //把过滤信息写到日志文件中
      //context.log(filterName+"页面被硬编码成gbk");
      filterChain.doFilter(request, response);
    /*}
    catch(ServletException sx) {
      filterConfig.getServletContext().log(sx.getMessage());
      System.out.println("encode过滤器1处发生错误"+sx.getMessage());
      sx.printStackTrace();
    }
    catch(IOException iox) {
      filterConfig.getServletContext().log(iox.getMessage());
      System.out.println("encode过滤器2处发生错误"+iox.getMessage());
    }*/
  }

  //Clean up resources
  public void destroy() {
  }
}
